package com.shire.shire_interface.controller.account;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.common.utils.StrUtils;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.dao.accounts.UserAccountDao;
import com.shire.shire_interface.model.accounts.UserAccount;
import com.shire.shire_interface.model.accounts.UserAccountExample;
import com.shire.shire_interface.model.command.WxCommand;
import com.shire.shire_interface.model.cs.WxChatExample;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.model.user.WxAccountExample;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.chat.WxChatService;
import com.shire.shire_interface.service.commandcenter.BaseCommandProcessor;
import com.shire.shire_interface.service.commandcenter.WxCommandService;
import com.shire.shire_interface.service.friend.WxFriendService;
import com.shire.shire_interface.service.group.WxGroupService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Api(tags = "客服")
@RestController
@RequestMapping("/account")
public class WxAccountController extends BaseController {

    @Resource
    private WxAccountService wxAccountService;
    @Resource
    private WxFriendService wxFriendService;
    @Resource
    private WxGroupService wxGroupService;
    @Resource
    private WxChatService wxChatService;
    @Resource
    private WxCommandService commandService;
    @Resource
    private BaseCommandProcessor commandProcessor;
    @Resource
    private UserAccountDao userAccountDao;

//    @ApiOperation(value = "微信账号列表 csid")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(paramType = "body", required = true, dataType = "WxAccount", name = "wxAccount")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @ResponseBody
    @PostMapping("/wxAccountsByCsId")
    public Response wxAccountList(@RequestBody WxAccount wxAccount, HttpSession session) {
        Response result = new Response();
        try {
            if (!checkLoginUserByCsId(session, wxAccount.getCsid())){
                result.error("请登录！");
                result.setCode(501);
                return result;
            }
            UserAccountExample userAccountExample = new UserAccountExample();
            userAccountExample.createCriteria().andUserIdEqualTo(getCurrentUser(session).getId());

            List<UserAccount> userAccounts = userAccountDao.selectByExample(userAccountExample);

            List<String> wxidList = new ArrayList<>();

            for (UserAccount ua : userAccounts){
                wxidList.add(ua.getWxAccount());
            }

            WxAccountExample example = new WxAccountExample();
            example.createCriteria().andWxidIn(wxidList);
            List<WxAccount> wxAccountsByCsId = wxAccountService.getWxAccountsByCsId(example);
            result.setData(wxAccountsByCsId);

            for (WxAccount account : wxAccountsByCsId) {
                WxChatExample wxChartExample = new WxChatExample();
                wxChartExample.createCriteria().andWxaccountEqualTo(account.getWxid()).andReadstatusEqualTo(1);
                Long aLong = wxChatService.countByExample(wxChartExample);
                account.setNoReadCnt(aLong);

            }
            result.success("成功");
        } catch (Exception e) {
            result.error("失败");
            e.printStackTrace();
        }
        return result;
    }

//    @ApiOperation(value = "修改账号信息 wxid")
    @ResponseBody
    @PostMapping("/updateWxAccount")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(paramType = "body", required = true, dataType = "WxAccount", name = "wxAccount")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    public Response updateWxAccount(@RequestBody JSONObject jsonBody, HttpSession session){
        Response result = new Response();
        Integer csId = jsonBody.getInteger("csId");
        String accountWxid =  jsonBody.getString("accountWxid");
        Integer gender = jsonBody.getInteger("gender");
        String signature = jsonBody.getString("signature");
        String nickname = jsonBody.getString("nickname");
        String imagedata = jsonBody.getString("imagedata"); // 头像base64
        String area = jsonBody.getString("area");

        if (!checkLoginUserByCsId(session, csId)){
            result.error("请登录！");
            result.setCode(501);
            return result;
        }

        WxAccount wxAccount = wxAccountService.getWxAccountByAccountName(csId, accountWxid);
        if(wxAccount==null ){
             result.error("微信账号不存在");
             return result;
        }
        Map<String,Object> reqMap = new HashMap<>();
        Constants.Sex accountGender = Constants.Sex.get(wxAccount.getGender());
        if(gender != null && !gender.equals(accountGender.getCode())){
            reqMap.put("gender", gender);
        }
        if(StrUtils.isNotBlank(signature) && !signature.equals(wxAccount.getSignature())){
            reqMap.put("signature", signature);
        }
        if(StrUtils.isNotBlank(nickname) && !nickname.equals(wxAccount.getNick())){
            reqMap.put("nickname", nickname);
        }
        if(StrUtils.isNotBlank(imagedata)){
            reqMap.put("imagedata", imagedata);
        }
        if(StrUtils.isNotBlank(area) && !area.equals(wxAccount.getArea())){
            reqMap.put("area", area);
        }
        if(reqMap.size()==0){
             result.error("没有需要修改的信息");
             return result;
        }
        WxCommand command = commandService.generateCmdObject(csId, wxAccount.getId(),JSONUtils.toJSONString(reqMap),WxConstants.CmdTaskType.UNKNOWN,0,WxConstants.CmdType.CRK_UPDATE_PROFILE_D,WxConstants.CmdPriority.UNKNOWN);
        commandProcessor.addCommand(csId,wxAccount.getId(),command);
        result.success("");
        return result;
    }

//    @ApiOperation(value = "添加账号信息 wxid")
    @ResponseBody
    @PostMapping("/add")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(paramType = "body", required = true, dataType = "WxAccount", name = "wxAccount")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    public Response addAccount(@RequestBody WxAccount wxAccount, HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            wxAccountService.insertWxAccount(wxAccount);
            response.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }

//    @ApiOperation(value = "同步通信录 post b\"同步失败\"+e.getMessage()ody 用json 传入wxAccount")
    @ResponseBody
    @PostMapping("/sync")
//    @ApiResponses({@ApiResponse(code = 200, message = "同步成功，请稍候", response = Response.class)})
    public Response syncAccountContacts(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            String wxAccount = jsonObject.getString("wxAccount");
            WxAccount account = wxAccountService.getWxAccountByWxId(wxAccount);
            WxCommand command = commandService.genSyncAddressCmd(account);
            commandProcessor.addCommand(getCurrentUser(session).getId(), account.getId(), command);
            response.success("同步成功，请稍候");
        }catch (Exception e){
            response.error("同步失败"+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }
}
